<?php
require_once dirname(__FILE__) . '/../includes/common.inc.php';
require_once dirname(__FILE__) . "/../database/$database/database.inc.php";
  
header('Content-Type: text/plain');

global $myManager;

$action = MiscUtils::getParam('action', NULL);

$myManager->start_t();
try {
  switch ($action) {
    case 'login':
      login($myManager);
      break;
    case 'expenses':
      expenses($myManager);
      break; 
    case 'iesumexpense':
      iesumexpense($myManager);
      break;
    case 'iesumexpenseparticular':
      iesumexpenseparticular($myManager);
      break;
    case 'iesumexpensedetail':
      iesumexpensedetail($myManager);
      break;
    default:
      break;
  }
} catch (PDOException $e) {
  echo $e->getMessage();
}
$myManager->commit_t();

function _months($from, $to) {
  $result = array();
  for ($i = $from->year, $il = $to->year; $i <= $il; $i++) {
    for ($j = 1, $jl = 12; $j <= $jl; $j++) {
      if ($i == $from->year && $j < $from->month) {
        continue;
      } else if ($i == $to->year && $j > $to->month) {
        continue;
      }
      $tmp = new stdClass();
      $tmp->month = $j;
      $tmp->year = $i;
      $result[] = $tmp;
    }
  }
  return $result;
}

function _days($year, $month) {
  if ($month == 1) {
    return 31;
  } else if ($month == 2) {
    if ($year % 4 == 0) {
      return 29;
    } else {
      return 28;
    }
  } else if ($month == 3) {
    return 31;
  } else if ($month == 4) {
    return 30;
  } else if ($month == 5) {
    return 31;
  } else if ($month == 6) {
    return 30;
  } else if ($month == 7) {
    return 31;
  } else if ($month == 8) {
    return 31;
  } else if ($month == 9) {
    return 30;
  } else if ($month == 10) {
    return 31;
  } else if ($month == 11) {
    return 30;
  } else if ($month == 12) {
    return 31;
  }
}

function login($myManager) {
  $orm = classToOrm('pz_user');
  $account = MiscUtils::getParam('a', NULL);
  $password = MiscUtils::getParam('p', START);

  $result = $orm->find($myManager, NULL, NULL, NULL, NULL, "d.account = '$account' AND d.password = '$password'", NULL);
  if (count($result->data) == 1) {
    $user = $result->data[0];
    $_SESSION[OPERATOR] = $user;
    
    setcookie(OPERATOR, json_encode($user), (time() + 3600), PATH, DOMAIN);
    
    echo json_encode($user);
  } else {
    echo json_encode(array());
  }
}


function expenses($myManager) {
  $function = MiscUtils::getParam('f', NULL);
  $condition = MiscUtils::getParam('c', NULL);
  $order = MiscUtils::getParam('o', NULL);
  $queue = MiscUtils::getParam('q', NULL);
  $page = MiscUtils::getParam('p', NULL);
  $size = MiscUtils::getParam('s', NULL);
  
  $createdFrom = MiscUtils::getParam('from', NULL);
  $createdTo = MiscUtils::getParam('to', NULL);
  
  $user = json_decode(MiscUtils::getParam('u', NULL));
  
  $condition .= ($createdFrom) ? ' AND (d.payDate >= \'' . SimpleDate::toStamp(json_decode($createdFrom)) . '\')' : '';
  $condition .= ($createdTo) ? ' AND (d.payDate <= \'' . SimpleDate::toStamp(json_decode($createdTo)) . '\')' : '';
  
  if ($user) {
    if ($user->type == USER_TYPE_STAFF) {
      $condition = $condition . " AND (d.userTrackId = '$user->trackId') ";
    } else {
      $condition = $condition;
    }
  }
  
  $orm = classToOrm('pz_expense');
  if ($orm) {
    try {
      $result = $orm->find($myManager, $page, $size, $order, $queue, $condition, $function);
      $result->total = count($orm->find($myManager, START, INFINITE, NULL, NULL, $condition, NULL)->data);
      echo json_encode($result);
    } catch (PDOException $e) {
      echo $e->getMessage();
    }
  }
}

function iesumexpense($myManager) {
  $function = MiscUtils::getParam('f', NULL);
  $condition = MiscUtils::getParam('c', '1 = 1');
  $order = MiscUtils::getParam('o', NULL);
  $queue = MiscUtils::getParam('q', NULL);
  $page = MiscUtils::getParam('p', NULL);
  $size = MiscUtils::getParam('s', NULL);
  
  $createdFrom = MiscUtils::getParam('from', NULL);
  $createdTo = MiscUtils::getParam('to', NULL);
  
  $user = json_decode(MiscUtils::getParam('u', NULL));
    
  $condition .= ($createdFrom) ? ' AND (d.payDate >= \'' . SimpleDate::toStamp(json_decode($createdFrom)) . '\')' : '';
  $condition .= ($createdTo) ? ' AND (d.payDate <= \'' . SimpleDate::toStamp(json_decode($createdTo)) . '\')' : '';
  
  if ($user) {
    if ($user->type == USER_TYPE_STAFF) {
      $condition = $condition . " AND (d.userTrackId = '$user->trackId') ";
    } else {
      $condition = $condition;
    }
  }
  $orm = classToOrm('pz_expense');
  if ($orm) {
    try {
      $result = $orm->find($myManager, $page, $size, $order, $queue, $condition, $function);
      $result->total = count($orm->find($myManager, START, INFINITE, NULL, NULL, $condition, NULL)->data);
      $exp = 0; $cash = 0; $noncash = 0; $rest = array(); $exist;
      for ($i = 0, $il = count($result->data); $i < $il; $i++) {
        $expense = $result->data[$i];
        if ($expense->status == -1) {
          continue;
        }
        $exp += $expense->amount;
        if ($expense->method == 'C') {
          $cash += $expense->amount;
        } else {
          $noncash += $expense->amount;
        }
        $exist = false;
        for ($j = 0, $jl = count($rest); $j < $jl; $j++) {
          $tmp = $rest[$j];
          if ($tmp->name == $expense->category) {
            $tmp->value += $expense->amount;
            $exist = true;
          }
        }
        if (!$exist) {
          $m = new stdClass();
          $m->name = $expense->category;
          $m->value = $expense->amount;
          array_push($rest, $m);
        }
      }
      $top = new stdClass();
      $top->expense = $exp;
      $top->cash = $cash;
      $top->noncash = $noncash;

      $months = _months(json_decode($createdFrom), json_decode($createdTo));

      $bottom = array();
      foreach ($months as &$tmp) {
        $start = SimpleDate::toStamp(SimpleDate::create($tmp->year, $tmp->month, 1));
        $end = SimpleDate::toStamp(SimpleDate::create($tmp->year, $tmp->month, _days($tmp->year, $tmp->month)));
        $b = new stdClass();
        $b->month = $tmp->month;
        $b->year = $tmp->year;
        $b->ecash = 0;
        $b->enoncash = 0;
        for ($j = 0, $jl = count($result->data); $j < $jl; $j++) {
          $expense = $result->data[$j];
          if ($expense->status == -1) {
            continue;
          }
          if (($start <= SimpleDate::toStamp($expense->createdDate)) && (SimpleDate::toStamp($expense->createdDate) <= $end)) {
            if ($expense->method == 'C') {
              $b->ecash += $expense->amount;
            } else {
              $b->enoncash += $expense->amount;
            }
          }
        }
        array_push($bottom, $b);
      }
      $res = new stdClass();
      $res->top = $top;
      $res->middle = $rest;
      $res->bottom = $bottom;
      echo json_encode($res);
    } catch (PDOException $e) {
      echo $e->getMessage();
    }
  }
}



function iesumexpenseparticular($myManager) {
  $function = MiscUtils::getParam('f', NULL);
  $condition = MiscUtils::getParam('c', NULL);
  $order = MiscUtils::getParam('o', NULL);
  $queue = MiscUtils::getParam('q', NULL);
  $page = MiscUtils::getParam('p', NULL);
  $size = MiscUtils::getParam('s', NULL);
  
  $createdFrom = MiscUtils::getParam('from', NULL);
  $createdTo = MiscUtils::getParam('to', NULL);
  
  $user = json_decode(MiscUtils::getParam('u', NULL));
  
  $condition .= ($createdFrom) ? ' AND (d.payDate >= \'' . SimpleDate::toStamp(json_decode($createdFrom)) . '\')' : '';
  $condition .= ($createdTo) ? ' AND (d.payDate <= \'' . SimpleDate::toStamp(json_decode($createdTo)) . '\')' : '';
  
  if ($user) {
    if ($user->type == USER_TYPE_STAFF) {
      $condition = $condition . " AND (d.userTrackId = '$user->trackId')";
    } else {
      $condition = $condition;
    }
  }
  $orm = classToOrm('pz_expense');
  if ($orm) {
    try {
      $result = $orm->find($myManager, $page, $size, $order, $queue, $condition, $function);
      $result->total = count($orm->find($myManager, START, INFINITE, NULL, NULL, $condition, NULL)->data);
      $rest = array(); $exist;
      $tol = 0;$cash = 0; $noncash = 0;
      for ($i = 0, $il = count($result->data); $i < $il; $i++) {
        $expense = $result->data[$i];
        if ($expense->status == -1) {
          continue;
        }
        $tol += $expense->amount;
        if ($expense->method == 'C') {
          $cash += $expense->amount;
        } else {
          $noncash += $expense->amount;
        }
        $exist = false;
        for ($j = 0, $jl = count($rest); $j < $jl; $j++) {
          $tmp = $rest[$j];
          if ($tmp->name == $expense->particular) {
            $tmp->value += $expense->amount;
            $exist = true;
          }
        }
        if (!$exist) {
          $m = new stdClass();
          $m->name = $expense->particular;
          $m->value = $expense->amount;
          array_push($rest, $m);
        }
      }
      
      $top = new stdClass();
      $top->expense = $tol;
      $top->cash = $cash;
      $top->noncash = $noncash;
      
      $res = new stdClass();
      $res->main = $rest;
      $res->top = $top;
      echo json_encode($res);
    } catch (PDOException $e) {
      echo $e->getMessage();
    }
  }
}

function iesumexpensedetail($myManager) {
  $function = MiscUtils::getParam('f', NULL);
  $condition = MiscUtils::getParam('c', NULL);
  $order = MiscUtils::getParam('o', NULL);
  $queue = MiscUtils::getParam('q', NULL);
  $page = MiscUtils::getParam('p', NULL);
  $size = MiscUtils::getParam('s', NULL);
  
  $createdFrom = MiscUtils::getParam('from', NULL);
  $createdTo = MiscUtils::getParam('to', NULL);
  
  $user = json_decode(MiscUtils::getParam('u', NULL));
  
  $condition .= ($createdFrom) ? ' AND (d.payDate >= \'' . SimpleDate::toStamp(json_decode($createdFrom)) . '\')' : '';
  $condition .= ($createdTo) ? ' AND (d.payDate <= \'' . SimpleDate::toStamp(json_decode($createdTo)) . '\')' : '';
  
  if ($user) {
    if ($user->type == USER_TYPE_STAFF) {
      $condition = $condition . " AND (d.userTrackId = '$user->trackId') ";
    } else {
      $condition = $condition;
    }
  }
  
  $orm = classToOrm('pz_expense');
  if ($orm) {
    try {
      $result = $orm->find($myManager, $page, $size, $order, $queue, $condition, $function);
      $result->total = count($orm->find($myManager, START, INFINITE, NULL, NULL, $condition, NULL)->data);
      $result1 = $orm->find($myManager, START, INFINITE, $order, $queue, $condition, $function);
      
      $topResult = array(); $mainResult = array();
      for ($i = 0, $il = count($result1->data); $i < $il; $i++) {
        $exp = $result1->data[$i];
        if ($exp->status == -1) {
          continue;
        }
        $exist = false;
        for ($j = 0, $jl = count($topResult); $j < $jl; $j++) {
          $t = $topResult[$j];
          if ($t->payee == $exp->payee) {
            $t->total += $exp->amount;
            if ($exp->method == 'C') {
              $t->cash += $exp->amount;
            } else {
              $t->noncash += $exp->amount;
            }
            $exist = true;
          }
        }
        if (!$exist) {
          $obj = new stdClass();
          $obj->payee = $exp->payee;
          $obj->total = $exp->amount;
          $obj->cash = ($exp->method == 'C') ? $exp->amount : 0;
          $obj->noncash = ($exp->method == 'C') ? 0 : $exp->amount;
          array_push($topResult, $obj);
        }
      }
      $res = new stdClass();
      $res->top = $topResult;
      echo json_encode($res);
    } catch (PDOException $e) {
      echo $e->getMessage();
    }
  }
}

?>